package com.base.webapp.util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Des3Util {
	public static final String CHAR_ENCODING = "UTF-8";

	public static String encode(String key, String data) {
		try {
			byte[] keyByte = key.getBytes("UTF-8");
			byte[] dataByte = data.getBytes("UTF-8");
			byte[] valueByte = des3Encryption(keyByte, dataByte);
			return new String(Base64.encode(valueByte), "UTF-8");
		} catch (Exception e) {
		}
		return null;
	}

	public static String decode(String key, String value) {
		try {
			byte[] keyByte = key.getBytes("UTF-8");
			byte[] valueByte = Base64.decode(value.getBytes("UTF-8"));
			byte[] dataByte = des3Decryption(keyByte, valueByte);
			return new String(dataByte, "UTF-8");
		} catch (Exception e) {
		}
		return null;
	}

	public static byte[] des3Encryption(byte[] key, byte[] data)
			throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
			IllegalBlockSizeException, IllegalStateException {
		SecretKey deskey = new SecretKeySpec(key, "DESede");
		Cipher c1 = Cipher.getInstance("DESede");
		c1.init(1, deskey);
		return c1.doFinal(data);
	}

	public static byte[] des3Decryption(byte[] key, byte[] data)
			throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
			IllegalBlockSizeException, IllegalStateException {
		SecretKey deskey = new SecretKeySpec(key, "DESede");
		Cipher c1 = Cipher.getInstance("DESede");
		c1.init(2, deskey);
		return c1.doFinal(data);
	}

	public static void main(String[] args) {
		System.out.println(encode("0000000000000000000000", "0000000000000000000000"));
	}
}
